<?php
declare (strict_types = 1);

namespace app\admin\controller\erp;

use app\admin\controller\AuthController;
use app\admin\model\erp\ErpAdverts;
use app\admin\model\erp\ErpAdvertsTypes;
use app\admin\model\erp\Vendors;
use app\admin\model\system\SystemMenus;
use bbweb\services\UtilService as Util;
use think\facade\Config;
use think\facade\Db;
use think\Request;

class Advert extends AuthController
{
    /**
     * 显示列表
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function index(Request $req)
    {
        if ($req->isAjax()) {
            $data = [];
            $page = $req->param('page/d', 1);
            $limit = $req->param('limit/d', 15);
            $query = ErpAdverts::where('type',1);
            // 条件搜索
            $type_id = $req->param('type_id/d', 0);
            if ($type_id) {
                $path = ErpAdvertsTypes::where('id', $type_id)->value('path');
                $query->where('tid', 'in', $path);
            }
            $name = $req->param('name');
            if (!is_null($name) && strlen($name)) {
                $query->where('name','like',"%$name%");
            }
            $query->order('id DESC');
            $data['count'] = $query->count('id');
            $data['data'] = $query->page($page,$limit)->select()->toArray();
            $data['code'] = 0;
            $data['msg'] = '';
            $gidTypes =ErpAdvertsTypes::column('name','id');
            $advert_type = Config::get('erp.advert_type');
            $advert_sys = Config::get('erp.advert_sys');
            $advert_scenes = Config::get('erp.advert_scenes');
            foreach ($data['data'] as &$val) {
                $val['scene_name'] = isset($advert_scenes[$val['scene']]) ? $advert_scenes[$val['scene']]['name'] : '--/--';
                $val['tid_type'] = isset($gidTypes[$val['tid']]) ? $gidTypes[$val['tid']] : '--/--';
                $val['type_type'] = isset($advert_type[$val['type']]) ? $advert_type[$val['type']] : '--/--';
                $val['sys_type'] = isset($advert_sys[$val['sys']]) ? $advert_sys[$val['sys']] : '--/--';
                $val['start_at'] = $val['start_at'] ? date('Y-m-d', $val['start_at']) : '--/--';
                $val['end_at'] = $val['end_at'] ? date('Y-m-d', $val['end_at']) : '--/--';
            }

            return json($data);
        }
        $sonAuth = SystemMenus::getSonAuth($req->controller(), $req->action(),array_keys($this->auth));

        $treeData = ErpadvertsTypes::typeAll(1);
        // 显示页面
        $this->assign('sonAuth', $sonAuth);
        $this->assign('treeData', $treeData);
        return $this->fetch();
    }

    /**
     * 创建资源.
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function add(Request $req)
    {
        if($req->isPost()) {
            $data = Util::postMore([
                ['name', ''],
                ['user_id', 0],
                ['scene', 0],
                ['tid', 0],
                ['type', 1],
                ['sys', 0],
                ['start_at', ''],
                ['end_at', ''],
                ['price', 0],
                ['url', ''],
                ['imgs', ''],
                ['times', 0],
            ], $req);
            $data['start_at'] = preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/s",$data['start_at']) ? strtotime($data['start_at']) : 0;
            $data['end_at'] = preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/s",$data['end_at']) ? strtotime($data['end_at'].' 23:59:59') : 0;
            //if (!$data['user_id']) $this->error('请选择广告客户');
            if (!$data['name']) $this->error('请输入广告名称');
            if (!$data['start_at'] || !$data['end_at']) $this->error('请设置广告周期');
            if (!$data['url']) $this->error('请设置链接地址');
            if (!$data['imgs']) $this->error('请设置广告资源');
            $data['times'] = intval($data['times']);
            if (!$data['times']) $this->error('请设置广告展示时长');
            if($data['times'] > 15 || $data['times'] < 3)  $this->error('广告展示时长只能在3～15秒之间');
            $data['create_at'] = time();
            $data['update_at'] = time();
            $res = ErpAdverts::create($data);
            if($res) {
                $this->success('操作成功!');
            } else {
                $this->error('操作失败');
            }
        }
        $treeData = ErpAdvertsTypes::typeAll(2);
        $users = Db::name('erp_vendors')->where('id','>', 1)->column('id,name,phone,type', 'id');
        $advert_type = Config::get('erp.advert_type');
        $advert_sys = Config::get('erp.advert_sys');
        $user_types = Config::get('erp.user_types');
        $advert_scenes = Config::get('erp.advert_scenes');
        $this->assign('users', $users);
        $this->assign('treeData', $treeData);
        $this->assign('advert_type', $advert_type);
        $this->assign('advert_sys', $advert_sys);
        $this->assign('user_types', $user_types);
        $this->assign('advert_scenes', $advert_scenes);
        return $this->fetch();
    }

    /**
     * 更新资源
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function edit(Request $req)
    {
        $id = intval($req->param('id/d'));
        if(!$id) $this->error('参数错误','', -1);
        $advert = ErpAdverts::where('id', $id)->find();
        if(!$advert) $this->error('参数错误','', -1);
        if($req->isPost()) {
            $data = [];
            if($req->param('change/d')) {
                $data['status'] = $req->param('status/d');
            } else {
                $data = Util::postMore([
                    ['name', ''],
                    ['user_id', 0],
                    ['scene', 0],
                    ['tid', 0],
                    ['type', 1],
                    ['sys', 0],
                    ['start_at', ''],
                    ['end_at', ''],
                    ['price', 0],
                    ['url', ''],
                    ['imgs', ''],
                    ['times', 0],
                ], $req);
                $data['start_at'] = preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/s", $data['start_at']) ? strtotime($data['start_at']) : 0;
                $data['end_at'] = preg_match("/^\d{4}-\d{1,2}-\d{1,2}$/s", $data['end_at']) ? strtotime($data['end_at'] . ' 23:59:59') : 0;
                //if (!$data['user_id']) $this->error('请选择广告客户');
                if (!$data['name']) $this->error('请输入广告名称');
                if (!$data['start_at'] || !$data['end_at']) $this->error('请设置广告周期');
                if (!$data['url']) $this->error('请设置链接地址');
                if (!$data['imgs']) $this->error('请设置广告资源');
                $data['times'] = intval($data['times']);
                if (!$data['times']) $this->error('请设置广告展示时长');
                if($data['times'] > 15 || $data['times'] < 3)  $this->error('广告展示时长只能在3～15秒之间');
            }
            $data['update_at'] = time();
            $res = ErpAdverts::where('id', $id)->update($data);
            if($res) {
                $this->success('操作成功!');
            } else {
                $this->error('操作失败');
            }
        }
        $treeData = ErpAdvertsTypes::typeAll(2);
        $users = Db::name('erp_vendors')->where('id','>', 1)->column('id,name,phone,type', 'id');
        $advert_type = Config::get('erp.advert_type');
        $advert_sys = Config::get('erp.advert_sys');
        $user_types = Config::get('erp.user_types');
        $advert_scenes = Config::get('erp.advert_scenes');
        $advert['start_at'] = $advert['start_at'] ? date('Y-m-d', $advert['start_at']) : '';
        $advert['end_at'] = $advert['end_at'] ? date('Y-m-d', $advert['end_at']) : '';
        $this->assign('users', $users);
        $this->assign('advert', $advert);
        $this->assign('treeData', $treeData);
        $this->assign('advert_type', $advert_type);
        $this->assign('advert_sys', $advert_sys);
        $this->assign('user_types', $user_types);
        $this->assign('advert_scenes', $advert_scenes);
        return $this->fetch();
    }

    /**
     * 显示分类列表
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function types(Request $req)
    {
        if ($req->isAjax()) {
            $array = ErpAdvertsTypes::typeAll();
            $this->success('ok','', $array, 0);
        }
        $sonAuth = SystemMenus::getSonAuth($req->controller(), 'index',array_keys($this->auth));
        // 显示页面
        $this->assign('sonAuth', $sonAuth);
        return $this->fetch();
    }

    /**
     * 创建分类.
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function addType(Request $req)
    {
        if ($req->isPost()) {
            $data = Util::postMore([
                'name',
                ['pid', 0]
            ], $req);
            if (!$data['name']) $this->error('请输入类别名称');
            $data['update_at'] = time();
            $res = ErpAdvertsTypes::create($data);
            if($res) {
                ErpAdvertsTypes::setPath();
                $this->success('操作成功!');
            } else {
                $this->error('操作失败');
            }
        }
        $pid = $req->param('pid/d',0);
        $parents = Db::name('erp_adverts_types')->where('pid',0)->order('id ASC')->column('name','id');
        $this->assign('parents',$parents);
        $this->assign('pid',$pid);
        return $this->fetch();
    }

    /**
     * 更新分类
     *
     * @param  \think\Request  $req
     * @return \think\Response
     */
    public function editType(Request $req)
    {
        $id = intval($req->param('id/d',0));
        $type = ErpAdvertsTypes::find($id);
        if(empty($type)) {
            $this->error('参数错误！','',-1);
        }
        if ($req->isPost()) {
            $data = [];
            if($req->param('change/d')) {
                $data['visable'] = $req->param('visable/d');
            } else {
                $data = Util::postMore([
                    'name',
                    ['pid', 0]
                ], $req);
                if (!$data['name']) $this->error('请输入类别名称');
            }
            $data['update_at'] = time();
            $res = ErpAdvertsTypes::where('id','=',$id)->update($data);
            if($res) {
                ErpAdvertsTypes::setPath();
                $this->success('操作成功!');
            } else {
                $this->error('操作失败');
            }
        }
        if(is_numeric($type['path']))
            $parents = Db::name('erp_adverts_types')->where('pid',0)->where('id','<>', $id)->order('id ASC')->column('name','id');
        else
            $parents = [];
        $this->assign('parents',$parents);
        $this->assign('type',$type);
        return $this->fetch();
    }

    /**
     * 获取客户信息
     * @param Request $req
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function public_get_user(Request $req)
    {
        $uid = intval($req->param('uid/d',0));
        if(!$uid) $this->error();
        $user = Vendors::find($uid);
        if(!$user) $this->error();
        $data = [];
        $data['name'] = $user['name'];
        if($user['sys']==1) {
            $data['users'][] = [
                'name' => $user['name'],
                'phone' => $user['phone'],
                'desc' => $user['description'],
                'address' => $user['address'].$user['detailed_address'],
                'position' => '',
                'email' => '',
            ];
        } else {
            $data['users'] = $user['link_mans'];
        }
        $this->success('ok','',$data,1);
    }

    public function public_test_advert() {
        $secret_key = 'sDFajhsDSjsaTq2w';
        $time = time();
        $sign = md5(md5($secret_key) . $time );
        $data = [
            'sign' => $sign,
            'timestamp'  => $time,
            'data' => ['idCard'=>'132628197705084510']
        ];
        $url = 'http://api.cklock.cn/get_advert';
        $data  = json_encode($data);
        $headerArray = array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        //halt($output);
        halt(json_decode($output, true));
    }
}
